<template>
  <div id="_map" style="width: 100%;height: 100%;min-width: 200px;min-height: 200px" class="gykj_map">
    <div v-if="options.showBottom" class="zoom-info-dialog">
      <div><span>经度：{{curLng}}</span></div>
      <div><span>纬度：{{curLat}}</span></div>
      <div><span>级别：{{curLevel}}</span></div>
      <div><span>当前：{{qhmc}}</span></div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import Cookies from 'js-cookie';
  import mapboxgl from 'mapbox-gl';
  import DrillDownLayer  from '../../common/DrillDownLayer'
  import MapCommon  from '../../common/MapCommon'

  export default {
    name: "MapContainer",
    props: {
      styleUrl: {
        type: String,
        default: "mapbox://styles/mapbox/streets-v11"
      },
      defaultLevel: {
        type: Number,
        default: null
      },
      defaultCenter: {
        type: Array,
        default: () => null
      },
      //认证类型,Authorization/Signature/''
      authType: {
        type: String,
        default: ''
      },
      options: {
        type: Object,
        default: function () {
          return {
            showBottom:true,
          }
        }
      },
      replaceUrl:{
        type:Array,
        default:()=>{
          return[]
        }
      }
    },
    data() {
      return {
        headers: null,
        map: null,
        curLevel: 0,
        curLng: 0,
        curLat: 0,
          qhmc:'',//当前视图中心点所处行政区
          qhdm:''

      };
    },
    created() {
      mapboxgl.accessToken = 'pk.eyJ1IjoiemhvdTM0MzQiLCJhIjoiY2wyNjR4ajFlMjFpazNicW9iczN6cGVzaCJ9.oxnj2y9lbyEg3s-k3SEFsQ';

      if (this.authType) {
        let token = Cookies.get("token") || localStorage.getItem('token');
        if (this.authType === "Authorization") {
          this.headers = {
            Authorization: token,
          }
        } else {
          this.headers = {
            Signature: token,
          }
        }
      }
    },
    mounted() {
      if (!this.headers) {
        this.initMap(this.styleUrl);
        return;
      }

      //请求style
      axios.get(this.styleUrl, {
        headers: this.headers//设置header信息
      }).then(res => {
        if (!res.data) {
          return
        }
        let style = res.data || {};
        this.initMap(style)
      }).catch(err => {
        console.error("获取style失败");
        console.error(err);
      });

    },
    methods: {
      //初始化地图
      initMap(style) {

        let option= {
          container: "_map",
          style: style,
          maxZoom: 16.99,
          dragRotate: false,
          pitchWithRotate: false,
          touchZoomRotate: true,
          refreshExpiredTiles: true,
          transformRequest: (url, resourceType) => {
            // 替换url
            if(this.replaceUrl&&this.replaceUrl.length>0){
              for (let i = 0; i < this.replaceUrl.length; i++) {
                let item=this.replaceUrl[i];
                if(url.includes(item.origin)){
                  url=url.replace(item.origin,item.target)
                }
              }
            }


            if (
              (url.includes("mse.gykj.com.cn") ||
                url.includes("mse.agribigdata.com.cn")) && this.headers
            ) {
              return {
                url: url,
                headers: this.headers,
              };
            } else {
              return {
                url: url,
              };
            }
          },
        };
        if(this.defaultLevel){
          option.zoom=this.defaultLevel;
        }
        if(this.defaultCenter){
          option.center=this.defaultCenter;
        }



        let map = new mapboxgl.Map(option);
        this.map = map;
        //解决canvas渲染不正确
        map.on("styledata", function () {
          map.resize();
        });
        map.on("load", (e) => {

          //底部文字提示激活
          if(this.options.showBottom){
            this.initBottom()
          }
          this.$emit("load", map);
        })
      },
      triggerRepaint(){
        if(this.map){
          this.map.triggerRepaint()
        }
      },
      initBottom(){
        //新增用于查询的图层
        for (let i = 0; i < DrillDownLayer.length; i++) {
          let lyrDrl = DrillDownLayer[i];
          //1增加透明的fill图层用于查询
          MapCommon.addClickLayer(this.map,lyrDrl.layerId,lyrDrl.layer_fill + "_search")
        }

        this.map.on("drag", this.mapDrag);
        this.map.on("zoomend", this.mapZoomEnd);
        this.map.on("moveend", this.mapMoveEnd);
        this.mapZoomEnd();

      },
      mapDrag: function () {
        this.curLng = this.map.getCenter().lng.toFixed(6);
        this.curLat = this.map.getCenter().lat.toFixed(6);
      },
      mapZoomEnd: function () {
        this.curLevel = this.map.getZoom().toFixed(2);
        this.curLng = this.map.getCenter().lng.toFixed(6);
        this.curLat = this.map.getCenter().lat.toFixed(6);
        //更新中心点落入的行政区划信息
        this.calCenterAdminArea()
      },
      mapMoveEnd: function () {
        //更新中心点落入的行政区划信息
        this.calCenterAdminArea()
      },
      calCenterAdminArea() {
        let map = this.map;
        let centPt = map.project(map.getCenter());

        let features = map.queryRenderedFeatures(centPt); //查询点击的要素

        let tempLvl = 6; /*一共六个级别*/
        let resLevel = -1;
        let res = null; /*最终结果*/
        features.forEach((feature) => {
          /*查找当前遍历元素对应的配置数据*/

          let lyrDrl = DrillDownLayer.find((lyr) => {
            return feature.layer.source === lyr.sourceId;
          });
          if (lyrDrl && lyrDrl.level <= tempLvl) {
            resLevel = lyrDrl.level;
            res = feature;
          }
        });

        this.qhmc = res ? res.properties.qhmc : "";
        this.qhdm = res ? res.properties.qhdm : "";
      },



    }
  }
</script>

<style scoped  lang="less">
  .zoom-info-dialog {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 1;
    font-size: 12px;
    height: 24px;
    text-align: center;

    div{
      width: 180px;
      border-right: 2px solid #fff;
      text-align: center;
      height: 14px;
      margin: 5px 0;
      display: inline-block;
    }

    span{
      color: #fff;
      position: relative;
      top: -3px;
      vertical-align: middle;
    }

    &last-child{
      border: none;
    }
  }
  @media screen and (max-width: 980px) {
    .zoom-info-dialog{
      height: 5%;
      div{
        height: 50%;
        float: left;
        width: 50%;
        margin: 0;
        border: 0;
        font-size: 2vh;
        line-height: 2.5vh;
        text-align: left;
        span{
        padding-left: 20px;
      }
      }
    }
  }



</style>
<style>
  @import url("https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css");
</style>
